<?php

namespace common\components\system;

use Yii;
use yii\db\BaseActiveRecord;
use yii\web\User;
use yii\web\Application;

/**
 * 系统日志记录器
 *
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class Loger {

    /**
     * 默认监听事件
     * @return array BaseActiveRecord's Events.
     */
    protected static function listens() {
        return [
            OperationRecord::class => [
                'class' => OperationRecord::class,
                'events' => [
                    BaseActiveRecord::EVENT_AFTER_FIND,
                    BaseActiveRecord::EVENT_AFTER_INSERT,
                    BaseActiveRecord::EVENT_AFTER_UPDATE,
                    BaseActiveRecord::EVENT_AFTER_DELETE,
                ]
            ],
            LoginRecord::class => [
                'class' => User::class,
                'events' => User::EVENT_AFTER_LOGIN,
            ],
            AccessRecord::class => [
                'class' => Application::class,
                'events' => Application::EVENT_AFTER_ACTION,
            ],
        ];
    }

    /**
     * 记录日志
     * @final
     */
    public static function record($event = null) {
//        if (!YII_ENV_PROD) {
//            return;
//        }
        foreach (self::listens() as $usage => $data) {
            $class = $data['class'];
            $events = (array) $data['events'];
            foreach ($events as $_event) {
                call_user_func_array(['\yii\base\Event', 'on'], [
                    $class,
                    $_event,
                    [
                        $usage,
                        $_event
                    ]
                ]);
            }
        }

//        $logClassName = \common\models\AdminLog::class;
//        foreach (self::listens() as $class => $events) {
//            $events = (array) $events;
//            foreach ($events as $e) {
////                \yii\base\Event::on(\yii\db\BaseActiveRecord::className(), \yii\db\BaseActiveRecord::EVENT_AFTER_INSERT, ['backend\components\AdminLog', 'write']);
////                \yii\base\Event::on(\yii\db\BaseActiveRecord::className(), \yii\db\BaseActiveRecord::EVENT_AFTER_UPDATE, ['backend\components\AdminLog', 'write']);
////                \yii\base\Event::on(\yii\db\BaseActiveRecord::className(), \yii\db\BaseActiveRecord::EVENT_AFTER_DELETE, ['backend\components\AdminLog', 'write']);
//                $params = [
//                    $class,
//                    $e,
//                    [
//                        $logClassName,
//                        $e
//                    ]
//                ];
//                call_user_func_array(['\yii\base\Event', 'on'], $params);
//            }
//        }
    }

}
